﻿

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WHLRDF.ORM;
using WHLRDF.Application.Model;
namespace WHLRDF.Application.BLL
{
    public class EmailService : SerivceBase, IEmailService
    {

        #region 基本方法
        /// <summary>
        /// 查询所有
        /// </summary>
        public List<EmailEntity> GetAll()
        {
            ICriterion criter = Expression.Eq(EmailEntity.__IsDeleted, false);
            return this.Query<EmailEntity>(criter).ToList();

        }
        /// <summary>
        /// 获取单个实例的方法
        /// <param name="id">object类型</param>
        /// </summary>
        public EmailEntity GetById(string id)
        {
            return this.GetById<EmailEntity>(id);

        }

        /// <summary>
        /// 保存方法
        /// <param name="entity">对象</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Save(EmailEntity entity, ref string strError)
        {

            if (string.IsNullOrWhiteSpace(entity.EmailId))
            {
                entity.EmailId = MyGenerateHelper.GenerateOrder();
            }
            // entity.OrgId = new WHLRDF.Application.BLL.SerialRuleService().CreateSerialNo(Organizations_Identity_Num, null, ref strError);// 主键生成值
            return this.SaveOrUpdate<EmailEntity>(entity);

        }
        /// <summary>
        /// 删除方法
        /// <param name="deleteKey">主键，如果字符串请将字符串列表用单引号将字符串用上,如（'aaa','bbb'）</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Delete(string deleteKey, ref string strError)
        {
            if (!string.IsNullOrEmpty(deleteKey))
            {
                return this.Delete<EmailEntity>(deleteKey);
            }
            return true;
        }
        /// <summary>
        /// 分页查询方法
        /// <param name="grid">分页查询的相关参数</param>
        /// </summary>
        public LigerGrid ForGrid(LigerGrid grid)
        {
            ICriterion criter = Expression.Eq("IsDeleted", false);
            if (!string.IsNullOrEmpty(grid.keyWord))
            {
                criter = Expression.And(criter,

                           Expression.Like(new string[] {
                                EmailEntity._PrimaryKeyName ,
                           }, grid.keyWord)
                           );
            }
            return this.Query<EmailEntity>(grid, criter);

        }
        #endregion

        #region 扩展方法

        /// <summary>
        /// 发送系统邮件
        /// </summary>
        /// <param name="toEmail"></param>
        /// <param name="title"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        public async Task<bool> Send(string toEmail, string title, string body)
        {
            return await Send(ApplicationEnvironments.Site.SMTP.SendAddress, "", 0, toEmail, "", title, body);
        }
        /// <summary>
        /// 通过模板发送邮件
        /// </summary>
        /// <param name="toEmail"></param>
        /// <param name="templateId"></param>
        /// <returns></returns>
        public async Task<bool> Send(string toEmail, string templateId,Dictionary<string,string> valuePairs)
        {
           var template=  this.GetById<TemplateEntity>(templateId);
            if (template == null)
            {
                return false;
            }
            if (valuePairs == null)
            {
                valuePairs = new Dictionary<string, string>();
            }
            if (!valuePairs.ContainsKey("SiteName"))
            {
                valuePairs.Add("SiteName",ApplicationEnvironments.ApplicationName);
            }
            if (valuePairs != null && valuePairs.Count > 0)
            {
                foreach (var item in valuePairs)
                {
                    template.Title = template.Title.Replace("@" + item.Key, item.Value);
                    template.Content = template.Content.Replace("@" + item.Key, item.Value);
                }
            }
            return await Send(ApplicationEnvironments.Site.SMTP.SendAddress, "", 0, toEmail, "", template.Title, template.Content);
        }
        public async Task<bool> Send(string sendUser, string formid, int formType,
            string toEmail, string ccuser, string title, string body)
        {
            string strError = "";
            bool flag = false;
            if (string.IsNullOrEmpty(title))
            {
                strError = "邮件标题不能为空";
                return false;
            }
            if (string.IsNullOrEmpty(body))
            {
                strError = "邮件内容不能为空";
                return false;
            }
            if (string.IsNullOrEmpty(toEmail))
            {
                strError = "收件人不能为空";
                return false;
            }
            EmailEntity entity = null;
            if (!string.IsNullOrEmpty(formid))
            {
                ICriterion criter = Expression.And(Expression.Eq(EmailEntity.__FormType, formType),
                    Expression.And(Expression.Eq(EmailEntity.__FormId, formid),
                    Expression.Eq(EmailEntity.__IsDeleted, false)));
                entity = this.Query<EmailEntity>(criter).FirstOrDefault();
            }
            if (entity == null)
            {
                entity = new EmailEntity
                {
                    CreateBy = ApplicationEnvironments.DefaultSession.UserId,
                    CreateDate = DateTime.Now,
                    LastModifyDate = DateTime.Now,
                    LastModifyUserId = ApplicationEnvironments.DefaultSession.UserId,
                    CCUser = ccuser,
                    ToUser = toEmail,
                    Content = body,
                    Title = title,
                    FormId = formid,
                    SendDate=DateTime.Now,
                    Status = 0,
                    FormType = formType.GetHashCode(),
                    SenderUser = sendUser,
                    SendResult = "",
                    SendRound = 0,
                  
                    UserId = ApplicationEnvironments.DefaultSession.UserId,
                    EmailId = MyGenerateHelper.GenerateOrder()
                };
            }

            if (entity.Status == 0)
            {
                try
                {
                    entity.SendRound += 1;
                    entity.LastModifyDate = DateTime.Now;
                    entity.ExpireTime = DateTime.Now;
                    entity.LastModifyUserId = ApplicationEnvironments.DefaultSession.UserId;
                    entity.Status = flag ? 1 : 2;
                    flag = await SmtpHelper.SmtpService.SendSync(ApplicationEnvironments.Site.SMTP.SendAddress, toEmail, title, body);
                   
                }
                catch (Exception ex)
                {
                    flag = false;
                    entity.Status = 2;
                   
                    entity.SendResult = ex.Message;
                }
                
            }
            this.SaveOrUpdate<EmailEntity>(entity, ref strError);
            return flag;
        }
        #endregion

    }
}